package com.zmx.patientend.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.patientend.BaseActivity;
import com.zmx.patientend.PatientsLocationAdapter;
import com.zmx.patientend.R;
import com.zmx.patientend.okhttp.OkHttp3ClientManager;
import com.zmx.patientend.utils.AllUtil;
import com.zmx.patientend.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 时间：2020/6/19 22:57
 * 功能：患者定位
 */
public class PatientsLocationActivity extends BaseActivity {

    LocationClient mLocationClient;  //定位客户端
    MapView mapView;  //Android Widget地图控件
    BaiduMap baiduMap;

    boolean isFirstLocate = true;
    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;


    private PatientsLocationAdapter adapter;
    private List<PatientsLocation> lists;



    @Override
    protected int getLayoutId() {
        return R.layout.activity_patients_location;
    }

    @Override
    protected void initViews() {

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
        } else {
            requestLocation();
        }
        setToolbar(R.id.tool_bar);
        ButterKnife.bind(this);

        LinearLayoutManager layout = new LinearLayoutManager(this);
        layout.setOrientation(LinearLayoutManager.HORIZONTAL);//设置为横向排列
        recycler_view.setLayoutManager(layout);

        adapter  = new PatientsLocationAdapter(mActivity);
        lists = new ArrayList<>();
        recycler_view.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                if (lists.get(listPosition).getLongitude() == 0 ||lists.get(listPosition).getLatitude()==0 ){

                    Toast("该患者未绑定手环");

                }else {

                    //设定中心点坐标
                    LatLng cenpt = new LatLng(lists.get(listPosition).getLatitude(),lists.get(listPosition).getLongitude());
                    //定义地图状态
                    MapStatus mMapStatus = new MapStatus.Builder()
                            .target(cenpt)
                            .zoom(18)
                            .build();
                    //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化

                    //构建Marker图标，设置位置圆点
                    BitmapDescriptor bitmap = BitmapDescriptorFactory
                            .fromResource(R.mipmap.dingwei);
                    //构建MarkerOption，用于在地图上添加Marker
                    OverlayOptions option = new MarkerOptions()
                            .position(cenpt)
                            .icon(bitmap);
                    baiduMap.addOverlay(option);


                    MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
                    //改变地图状态
                    baiduMap.setMapStatus(mMapStatusUpdate);
                    Toast("定位成功");
                }



            }
        });

        getPosition();



    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(this, "没有定位权限！", Toast.LENGTH_LONG).show();
                    finish();
                } else {
                    requestLocation();
                }
        }
    }

    private void requestLocation() {

        initLocation();
        mLocationClient.start();

    }

    private void initLocation() {
        //初始化
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_patients_location);

        mapView = findViewById(R.id.bmapView);

        baiduMap = mapView.getMap();
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(15.0f);
        baiduMap.setMapStatus(msu);

        LocationClientOption option = new LocationClientOption();
        //设置扫描时间间隔
//        option.setScanSpan(1000);
        //设置定位模式，三选一
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        //设置需要地址信息
        option.setIsNeedAddress(true);
        //保存定位参数
        mLocationClient.setLocOption(option);

    }


//    @OnClick({R.id.relayout1, R.id.relayout2})
//    public void onViewClicked(View view) {
//        switch (view.getId()) {
//            case R.id.relayout1:
//
//                //设定中心点坐标
//                LatLng cenpt = new LatLng(29.806651,121.606983);
//                //定义地图状态
//                MapStatus mMapStatus = new MapStatus.Builder()
//                        .target(cenpt)
//                        .zoom(18)
//                        .build();
//                //定义MapStatusUpdate对象，以便描述地图状态将要发生的变化
//
//                //构建Marker图标，设置位置圆点
//                BitmapDescriptor bitmap = BitmapDescriptorFactory
//                        .fromResource(R.mipmap.dingwei);
//                //构建MarkerOption，用于在地图上添加Marker
//                OverlayOptions option = new MarkerOptions()
//                        .position(cenpt)
//                        .icon(bitmap);
//                baiduMap.addOverlay(option);
//
//
//                MapStatusUpdate mMapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mMapStatus);
//                //改变地图状态
//                baiduMap.setMapStatus(mMapStatusUpdate);
//
//                break;
//            case R.id.relayout2:
//                Toast("该设备已离线。");
//                break;
//        }
//    }

    //内部类，百度位置监听器
    private class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {

            if (bdLocation.getLocType() == BDLocation.TypeGpsLocation || bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                navigateTo(bdLocation);
            }
        }
    }

    private void navigateTo(BDLocation bdLocation) {
        if (isFirstLocate) {
            LatLng ll = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
            baiduMap.animateMapStatus(update);
            isFirstLocate = false;
        }
    }

    //MapView生命周期
    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
    }


    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler(){

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what){

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());

                        JSONArray data = object.getJSONArray("data");

                        for (int i = 0;i<data.length();i++){

                            JSONObject pp = data.getJSONObject(i);

                            PatientsLocation pl = new PatientsLocation();
                            pl.setId(pp.getInt("id"));
                            pl.setMember_id(pp.getInt("member_id"));
                            pl.setPatient_id(pp.getInt("patient_id"));
                            pl.setName(pp.getString("name"));
                            pl.setAvatar(pp.getString("avatar"));

                            if (!pp.isNull("loc")) {

                                JSONObject loc = pp.getJSONObject("loc");

                                pl.setLatitude(loc.getDouble("latitude"));
                                pl.setLongitude(loc.getDouble("longitude"));

                            }else{

                                pl.setLatitude(0);
                                pl.setLongitude(0);

                            }


                            lists.add(pl);

                        }

                        adapter.setListAndNotifyDataSetChanged(lists);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };


    public void getPosition() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getPosition");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }


}
